import type cardType from "@/ts/cardType/cardType";
import { checkCardType } from "@/ts/cardType/cardType";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useCardTypeList = defineStore("cardTypeList", () => {
    const storgedCardType = ref({} as { [Index: string]: { type: cardType, time: number } })

    function saveType(type: cardType, saveName?: string, overWrite?: boolean) {
        let newName = saveName || null
        if (newName == null) {
            newName = '未命名' + new Date().toLocaleString()
        }
        if (!overWrite) {
            while (newName in storgedCardType.value) {
                newName += '_'
            }
        }
        storgedCardType.value[newName] = {
            type: type,
            time: new Date().getTime()
        }
    }
    
    const listByTime = computed(() => {
        return Object.keys(storgedCardType.value).sort((a,b)=>{return storgedCardType.value[b].time-storgedCardType.value[a].time})
    })
    function deleteType(id?:string){
        if(id==null) return false
        return delete storgedCardType.value[id]
    }
    return { storgedCardType, saveType,deleteType,listByTime }
}, {
    persist: {
            serializer: {
                serialize(data) {
    
                    return JSON.stringify(data)
                },
                deserialize(data) {
                    let state = JSON.parse(data)
                    let typeList = state.storgedCardType
                    if(typeof typeList =='object'){
                        let result:{ [Index: string]: { type: cardType, time: number } } = {}
                        for (const key of Object.keys(typeList)) {
                            if(typeof typeList[key].time == 'number'&& 'type' in typeList[key]){
                                let type = checkCardType(typeList[key].type)
                                if(type)result[key]={
                                    type:type,
                                    time:typeList[key].time
                                }
                            }
                        }
                        state.storgedCardType=result
                    }else{state.storgedCardType=[]}
                    return state
                },
            }
        }
})